var $clueTable = $('#clueTableList');//线索清单表格
var poolCategory = '';//线索池类别(区分是私有池、分公司公有池、全国公有池和个人池)
var poolState = '';//线索池状态(开启/停用)
var poolPermissionFlag = false;//是否显示权限与详情tab页
var optionObj = [];//管理组人员id
var arrOption = [];
var mainTreeData = [];
var changeFlag = false;
var peopleOptionObj = [];
var cluePollId = $('#poolId').val();
var choosePeopleId = [];
var echartsMonth = [];
var receiveCountList = [];
var conversionCountList = [];
$(function () {
    getEachartData();
    getClueData();
    RegSelect();
    loadAllCompanyList();
    poolCategory = $('#poolCategory').val();//线索池类别
    poolState = $('#poolState').val();//线索池状态(开启/停用)
    poolPermissionFlag = $('#poolPermissionFlag').val();//是否显示权限与详情tab页
    $('#fenpeiguize').css('display', 'none');
    $('#example-tags').css('display', 'none');
    $("#selfPool").css('display', 'none');
    $("#allPool").css('display', 'none');

    if(poolPermissionFlag == 'false'){//是否显示权限与详情tab页
        $('#settingsBasic').css('display', 'none');
    }
    if (poolCategory == 0) {//个人池
        $('#profileBasic').css('display', 'none');
        $('#messagesBasic').css('display', 'none');
        $('#settingsBasic').css('display', 'none');
        $('#clueStateSelect').css('display', 'none');
        $('#buttonGroupMain').css('display', 'none');
    }
    if (poolCategory == 2 || poolCategory == 3) { // 全国、分公司
        $('#settingsBasic').css('display', 'none');
        $("#allPool").css('display', 'block');
    }
    if (poolCategory == 1) {//私有池
        $("#selfPool").css('display', 'block');
    }

    clueTableListInit();//初始化线索清单表格
    selectCompany();
    $("#dimSearch").html('<li id="noPeople"><span>暂无数据</span></li>');
    onDropdownShow();
    getRightPeople();
    reShowFun(mainTreeData);
    companyselectShow();

    /* 线索池规则设置-被动分配人员名单 */
    getCompany();
    $('#fenpeiguize select').selectpicker({
        sanitize: true,
        size: 10
    });

    /* 高级筛选 */
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetData('#filterContent');
    });
    $('.filter-content select').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 8
    });
    $('.custom-group input[type="checkbox"]').click('click', function () {
        let customGroup = $(this).parents('.custom-group');
        if ($(this).prop('checked')) {
            // 自定义条件筛选
            customGroup.addClass('custom-active');
            customGroup.find('select').attr('disabled', 'disabled').find('option:first').prop('selected', 'selected');
            customGroup.find('select').selectpicker('refresh');
        } else {
            // 默认条件筛选
            customGroup.removeClass('custom-active');
            customGroup.find('select').removeAttr('disabled').selectpicker('refresh');
            $(this).parents('.custom-box').find('input[type="text"]').val('');
        }
    });
});

function confirmCompany() {
    peopleOptionObj = [];
    let arrPeopleOption = [];
    for (let k = 0; k < $("#quanxianCompanySelect option:selected").length; k++) {
        let tem = $("#quanxianCompanySelect option:selected")[k];
        arrPeopleOption.push(tem.innerText);
        peopleOptionObj.push(tem.value);
    }
    let strPeopleTag = '';
    for (let y = 0; y < arrPeopleOption.length; y++) {
        strPeopleTag += '<span>' + arrPeopleOption[y] + '</span>';
    }

    $('#alreadyChooseCompany').html('').append(strPeopleTag);
}

var choosePeopleId = [];

function changePeople(obj) {
    choosePeopleId = $(obj).val();
}

// 点击确定
function confirmCompany2() {
    // $('#chooseCompanyPeople').html('<span>已选公司--人员：</span>');
    $('#chooseCompanyPeople').html('');
    let selectCompanyId = $('#companyMultiple option:selected').val();
    if (choosePeopleId == null) {
        // 人员列表全部取消
        for (let m = 0; m < mainTreeData.length; m++) {
            if (mainTreeData[m].companyId === selectCompanyId) {
                for (let s = 0; s < mainTreeData[m].account.length; s++) {
                    mainTreeData[m].account[s].selected = false;
                }
            }
        }
    } else {
        if (choosePeopleId.length == 0) {
            // 未进行操作直接点击确定
            alert('您还未进行修改');
        } else {
            // 改变人员列表之后进行确认操作
            for (let m = 0; m < mainTreeData.length; m++) {
                if (mainTreeData[m].companyId === selectCompanyId) {
                    for (let s = 0; s < mainTreeData[m].account.length; s++) {
                        mainTreeData[m].account[s].selected = false;
                    }
                }
            }

            if (choosePeopleId !== null) {
                for (let i = 0; i < choosePeopleId.length; i++) {
                    // 选中的id
                    // console.log('下拉菜单选中的id：' + choosePeopleId[i])
                    for (let m = 0; m < mainTreeData.length; m++) {
                        if (mainTreeData[m].companyId === selectCompanyId) {
                            for (let s = 0; s < mainTreeData[m].account.length; s++) {
                                if (choosePeopleId[i] === mainTreeData[m].account[s].accountId) {
                                    mainTreeData[m].account[s].selected = true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    reShowFun(mainTreeData)
}

function reShowFun(list) {
    let reShow = [];
    for (let w = 0; w < list.length; w++) {
        if (list[w].account && list[w].account.length) {
            for (let v = 0; v < list[w].account.length; v++) {
                let obj = {};
                if (list[w].account[v].selected) {
                    obj.peopleName = list[w].account[v].userName;
                    obj.companyName = list[w].companyName;
                    reShow.push(obj)
                }
            }
        }
    }
    let tempArr = [], newArr = [];
    for (let i = 0; i < reShow.length; i++) {
        if (tempArr.indexOf(reShow[i].companyName) === -1) {
            newArr.push({
                companyName: reShow[i].companyName,
                peopleName: [reShow[i].peopleName]
            });
            tempArr.push(reShow[i].companyName);
        } else {
            for (let j = 0; j < newArr.length; j++) {
                if (newArr[j].companyName == reShow[i].companyName) {
                    newArr[j].peopleName.push(reShow[i].peopleName)
                }
            }
        }
    }
    // console.log(tempArr, newArr)
    let strHtml = '';
    for (let u = 0; u < newArr.length; u++) {
        let peopleStr = '';
        let mainStr = '';
        for (let b = 0; b < newArr[u].peopleName.length; b++) {
            peopleStr += '<span>' + newArr[u].peopleName[b] + '</span>';
        }
        mainStr = '<strong>' + newArr[u].companyName + '</strong>' + peopleStr;
        strHtml += '<p>' + mainStr + '</p>'
    }
    $('#chooseCompanyPeople').append(strHtml);
}

// 右侧获取人员
function getRightPeople() {
    getPeopleById(mainTreeData[0].account);
    let mark = [];
    for (let x = 0; x < mainTreeData[0].account.length; x++) {
        mark.push({
            value: mainTreeData[0].account[x].accountId,
            label: mainTreeData[0].account[x].userName,
            selected: mainTreeData[0].account[x].selected
        });
    }
    $('#peopleSelect').multiselect("destroy").multiselect({
        maxHeight: 350,
        includeSelectAllOption: true,
        dropRight: true,
        buttonText: function(options, select) {
            return '请选择';
        },
        onChange: function () {
            confirm();
        },
        onSelectAll: function () {
            confirm();
        },
        onDeselectAll: function () {
            confirm();
        }
    });

    $("#peopleMultiple").multiselect('dataprovider', mark);
    confirm();
}

function RegSelect() {
    $.ajax({
        url: '/cluePoolCompany/selectPoolPersonalPermission?cluePollId=' + cluePollId,
        async: false,
        type: "get",
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                mainTreeData = data.data;
                renderCompany(mainTreeData);
            }
        }
    });
}

function renderCompany(list) {
    var html = "";
    for (var i = 0; i < list.length; i++) {
        html += '<option value="' + list[i].companyId + '" >' + list[i].companyName
            + '</option>';
    }
    $("#companyMultiple").html(html);
    $('#companyMultiple').selectpicker('refresh');
}

// 切换公司
function changecompany(obj) {
    changeFlag = true;
    for (let m = 0; m < mainTreeData.length; m++) {
        if ($(obj).val() == mainTreeData[m].companyId) {
            getPeopleById(mainTreeData[m].account);
            // 切换公司直接替换右侧人员列表
            let mark = [];
            for (let x = 0; x < mainTreeData[m].account.length; x++) {
                mark.push({
                    value: mainTreeData[m].account[x].accountId,
                    label: mainTreeData[m].account[x].userName,
                    selected: mainTreeData[m].account[x].selected
                });
            }
            $("#peopleMultiple").multiselect('dataprovider', mark);
            return;
        }
    }
}
function getPeopleById(list) {
    $('#peopleMultiple').multiselect("destroy").multiselect({
        // nonSelectedText: '--请选择--',
        enableFiltering: true,
        includeSelectAllOption: true,
        maxHeight: 300,
        dropRight: true,
        buttonText: function(options, select) {
            return '请选择';
        },
        onChange: function () {
            changePeople(this.$select[0]);
            confirmCompany2();
        },
        onSelectAll: function () {
            changePeople(this.$select[0]);
            confirmCompany2();
        },
        onDeselectAll: function () {
            changePeople(this.$select[0]);
            confirmCompany2();
        }
    })
}

function eachartsFun(receiveCountList, conversionCountList, echartsMonth) {
    var myChart = echarts.init(document.getElementById('main'));
    var option = {
        title: {
            text: "线索池领取/转换数据",
            top: 30,
            left: 'center',
            textStyle: {
                fontSize: 18,
                color: '#283d68'
            }
        },
        legend: {
            top: 70,
            left: "center",
            data: ["领取数量", "转换数量"],
            itemGap: 20,
            textStyle: {
                padding: [2, 0, 0, 0]
            }
        },
        grid: {
            top: 120,
            bottom: 60,
            right: '6%',
            left: '8%'
        },
        tooltip: {},
        xAxis: {
            name: "日期",
            nameTextStyle: {
                verticalAlign: 'top'
            },
            data: echartsMonth,
            axisTick: {
                alignWithLabel: false,
                length: 4,
                lineStyle: {
                    color: '#c0c2d2'
                }
            },
            axisLine: {
                lineStyle: {
                    color: '#c0c2d2'
                }
            },
            axisLabel: {
                margin: 16,
                fontSize: 12,
                color: '#969696'
            }
        },
        yAxis: {
            name: "数量",
            nameTextStyle: {
                verticalAlign: 'bottom',
                align: 'right',
                padding: [0, 16, 10, 0],
                color: '#8c8c8c'
            },
            boundaryGap: false,
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
            axisLabel: {
                margin: 16,
                fontSize: 12,
                color: '#8c8c8c'
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#d9d9d9'
                }
            },
        },
        series: [
            {
                name: "领取数量",
                type: "line",
                lineStyle: {
                    color: '#5b8ff9'
                },
                itemStyle: {
                    color: '#5b8ff9',
                    borderColor: '#5b8ff9',
                    borderWidth: 2,
                },
                data: receiveCountList,
                smooth: true
            },
            {
                name: "转换数量",
                type: "line",
                lineStyle: {
                    color: '#2acc85'
                },
                itemStyle: {
                    color: '#2acc85',
                    borderColor: '#2acc85',
                    borderWidth: 2,
                },
                data: conversionCountList,
                smooth: true
            }
        ]
    };
    myChart.setOption(option);
    // 浏览器宽度变化更新图表尺寸
    window.addEventListener('resize', function () {
        myChart.resize();
    });
    // 数据统计标签页显示时更新图表
    $('a[href="#messages-basic"]').on('shown.bs.tab', function (e) {
        myChart.resize();
    });
}
// 获取图表数据
function getEachartData() {
    var poolId = $("#poolId").val();
    $.ajax({
        url: "/cluePoolStatistics/cluePoolReceiveConversionStatistics?cluePoolId="+poolId+"&monthCount=12",
        async: false,
        type: "get",
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                if (data.data.length) {
                    for (let i=0;i<data.data.length;i++) {
                        echartsMonth.push(data.data[i].yearMonth);
                        receiveCountList.push(data.data[i].receiveCount);
                        conversionCountList.push(data.data[i].conversionCount)
                    }
                    eachartsFun(receiveCountList, conversionCountList, echartsMonth)
                }
            }
        }
    })
}
function directSelectPeople(userName, userId) {
    $('#choosedPeopleName').text(userName);
    $('#choosedPeopleId').val(userId);
}

/**
 * 加载全部公司信息(全国公有池分配--公司下拉)
 */
function loadAllCompanyList() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelectAll").html("");
            $('#companySelectAll').append(companyOptionHtml);
            $('#companySelectAll').selectpicker('refresh');
            loadPersonByCompanyId(data.data[0].companyId);
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companySelectAll']").on("change", function () {
        loadPersonByCompanyId($(this).val());
    });
}

/**
 * 根据公司ID查询人员信息(加载分配人员下拉)
 * @param companyId
 */
function loadPersonByCompanyId(companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var personDiv = '';
            data.data.map(function (item) {
                personDiv += '<div class="radio-box-my">' +
                    '<input name="people" type="radio" value="' + item.accountId + '"/>' +
                    item.userName +
                    '</div>';
            });
            $('.tip-content').html('');
            $('.tip-content').html(personDiv);
        }
    });
}

/**
 * 加载分公司信息(分公司公有池--分配)
 */
function loadBranchCompanyList(cluePollId) {
    $.getJSON("/clue/selectBranchCompany?cluePollId=" + cluePollId, function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#quanxianBox").html("");
            $('#quanxianBox').append(companyOptionHtml);
            $('#quanxianBox').selectpicker('refresh');
            $("#companySelectAll").html("");
            $('#companySelectAll').append(companyOptionHtml);
            $('#companySelectAll').selectpicker('refresh');
            loadPersonByCompanyId(data.data[0].companyId);
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companySelectAll']").on("change", function () {
        loadPersonByCompanyId($(this).val());
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='quanxianBox']").on("change", function () {
        $('#peopleSelectByCompanyId').html('');
        loadPersonByCompanyId($(this).val());
    })
}

/**
 * 加载私有池拥有使用权限的公司和人员(私有池--分配)}
 */
function loadPrivateCompanyAndPerson(cluePollId) {
    $.getJSON("/cluePoolCompany/selectCompanyByDistributePermission?cluePollId=" + cluePollId, function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelect").html("");
            $('#companySelect').append(companyOptionHtml);
            $('#companySelect').selectpicker('refresh');
            loadPersonByCompanyId(data.data[0].companyId);
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companySelect']").on("change", function () {
        loadPersonByCompanyId($(this).val());
    });

    //加载私有池人员
    $.getJSON("/cluePoolCompany/selectPersonByDistributePermission?cluePollId=" + cluePollId, function (data) {
        if (data.code == '000000') {
            console.log('44444', data.data);
            var personOptionHtml = '';
            data.data.map(function (item) {
                personOptionHtml += '<option value="' + item.peopleId + '">' + item.peopleName + '</option>';
            });
            $("#peopleSelectDialog").html("");
            $('#peopleSelectDialog').append(personOptionHtml);
            $('#peopleSelectDialog').selectpicker('refresh');
        }
    });
}

/**
 * 分配选人--根据用户名查询其人员信息及公司名
 */
function selectPeopleByName() {
    var userName = $("#userName").val();//用户名
    var poolId = $("#poolId").val();//线索池ID
    if (poolCategory == 3) {//线索池类别(全国公有池)
        $.getJSON("/clue/selectUserAndCompanyByName?userName=" + userName, function (data) {
            if (data.code == '000000') {
                let str = '';
                if (data.data.length) {
                    $('#noPeople').css('display', 'none');
                    data.data.map(function (item) {
                        str += '<li><span onclick="directSelectPeople(\'' + item.userName + '\',\'' + item.accountId + '\')">' + item.userName + '(' + item.companyName + ')</span></li>'
                    });
                    $("#dimSearch").html('');
                    $("#dimSearch").html(str);
                } else {
                    $("#dimSearch").html('<li id="noPeople"><span>暂无数据</span></li>');
                }
            }
        });
        return;
    }

    if (poolCategory == 2) {//线索池类别(分公司公有池)
        $.getJSON("/clue/selectUserByPoolPermission?cluePollId=" + poolId + "&userName=" + userName, function (data) {
            if (data.code == '000000') {
                let str = '';
                if (data.data.length) {
                    $('#noPeople').css('display', 'none');
                    data.data.map(function (item) {
                        str += '<li><span onclick="directSelectPeople(\'' + item.userName + '\',\'' + item.accountId + '\')">' + item.userName + '（' + item.companyName + '）</span></li>'
                    });
                    $("#dimSearch").html('');
                    $("#dimSearch").html(str);
                } else {
                    $('#noPeople').css('display', 'block');
                }
            }
        });
    }
    // $.getJSON("/clue/selectUserAndCompanyByName?userName=" + userName, function (data) {
    //     if (data.code == '000000') {
    //         $("#dimSearch").html('');
    //         if (data.data.length) {
    //             let str = '';
    //             data.data.map(function (item) {
    //                 str += '<li><span onclick="directSelectPeople(\'' + item.userName + '\')">' + item.userName + '（' + item.companyName + '）</span></li>'
    //             });
    //             $("#dimSearch").html(str);
    //         } else {
    //             $("#dimSearch").html('<li id="noPeople"><span>暂无数据</span></li>');
    //         }
    //     }
    // });
}

// 右2
function selectCompany() {
    $('#quanxianCompanySelect').multiselect("destroy").multiselect({
        // nonSelectedText: '--请选择公司--',
        enableFiltering: true,
        includeSelectAllOption: true,
        maxHeight: 300,
        dropRight: true,
        buttonText: function(options, select) {
            return '请选择';
        },
        onChange: function () {
            confirmCompany();
        },
        onSelectAll: function () {
            confirmCompany();
        },
        onDeselectAll: function () {
            confirmCompany();
        }
    });
}

function companyselectShow() {
    $.ajax({
        url: "/cluePoolCompany/selectPoolCompanyPermission?cluePollId=" + cluePollId,
        async: false,
        type: "get",
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                let mark = [];
                for (let i = 0; i < data.data.length; i++) {
                    mark.push({
                        value: data.data[i].companyId,
                        label: data.data[i].companyName,
                        selected: data.data[i].selected
                    });
                }
                $("#quanxianCompanySelect").multiselect('dataprovider', mark);
                confirmCompany()
            }
        }
    })
}

function onDropdownShow() {
    //线索池id
    var poolId = $("#poolId").val();
    //获取公司id
    var companyId = $("#companyId").val();
    $.ajax({
        url: "/cluePoolManager/selectCluePoolManagerPeopleList?companyId=" + companyId + "&cluePoolId=" + poolId,
        async: false,
        type: "get",
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                var mark = [];
                for (let i = 0; i < data.data.length; i++) {
                    mark.push({
                        value: data.data[i].accountId,
                        label: data.data[i].userName,
                        selected: data.data[i].selected
                    });
                }
                $("#peopleSelect").multiselect('dataprovider', mark);
            }
        }
    })
}

function confirm() {
    $('#example-tags').html('');
    if ($('#peopleSelect').val()) {
        $("#nothing").css('display', 'none');
        $('#example-tags').css('display', 'inline-block');
        var arrOption = [];
        for (let m = 0; m < $("#peopleSelect option:selected").length; m++) {
            let obj = {};
            obj.id = $('#peopleSelect').val()[m];
            arrOption.push($("#peopleSelect option:selected")[m].innerText);
            optionObj.push(obj);
        }
        let strTag = '';
        for (var k = 0; k < arrOption.length; k++) {
            strTag += '<span>' + arrOption[k] + '</span>'
        }
        $('#example-tags').append(strTag);
    }
}

/**
 * 个人池、私有池、分公司公有池、全国公有池线索清单
 */
function clueTableListInit() {
    var defaultMark = $('#defaultMark').val();//是否是默认池
    $clueTable.bootstrapTable('destroy');//先销毁表格
    $clueTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/clue/selectClueList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        sortName: 'inPoolTime',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'clueId',
        idField: 'clueId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数

        fixedColumns: true,
        fixedNumber: 1,
        fixedRightNumber: 1,

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'clueId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', formatter: indexFormat},
            {title: '线索ID', field: 'clueNumber', align: 'left', valign: 'middle'},
            {title: '公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '联系人', field: 'contactPerson', align: 'left', valign: 'middle'},
            {title: '电话', field: 'contactPersonPhone', align: 'left', valign: 'middle'},
            {title: '职务', field: 'job', align: 'left', valign: 'middle'},
            {title: '线索来源', field: 'source', sortable: true, align: 'left', valign: 'middle'},
            {title: '线索评级', field: 'rating', align: 'left', valign: 'middle'},
            {title: '线索状态', field: 'clueState', sortable: true, align: 'left', valign: 'middle'},
            {title: '在池时间', field: 'inPoolTime', sortable: true, align: 'left', valign: 'middle'},
            {title: '领取次数', field: 'collectionTimes', align: 'left', valign: 'middle'},
            {title: '退回次数', field: 'returnTimes', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', events: operateEvents, formatter: genderOpt},
            {title: '线索池私有id', field: 'cluePoolPrivateId', visible: false}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            if (poolCategory != 0) {//非个人池
                $clueTable.bootstrapTable('hideColumn', 'contactPerson');//联系人
                $clueTable.bootstrapTable('hideColumn', 'contactPersonPhone');//联系电话
                $clueTable.bootstrapTable('hideColumn', 'job');//职务
            } else if(poolCategory == 0) {//个人池
                //$clueTable.bootstrapTable('hideColumn', 'clueState');//线索状态
                if (defaultMark == 0) {//个人默认池
                    $clueTable.bootstrapTable('hideColumn', 'collectionTimes');//领取次数
                    $clueTable.bootstrapTable('hideColumn', 'returnTimes');//退回次数
                }
            }
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table操作列下拉菜单效果
            tableNav();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
    /*$("#clueTableList").colResizable({
        liveDrag: true,
        resizeMode: 'overflow',
        partialRefresh: true
    });*/
}
/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    var allocation = $('#allocation').val();//分配方式
    let html = '';
    if (poolCategory == 0) {    //线索池类别(个人池只有查看)
        html = '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    } else {
        html = '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
        if (allocation == 0) {  //分配方式(混合模式)
            html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
            html += '<li><a href="#!" id="distribution">分配</a></li>';
            html += '<li><a href="#!" id="retrieve">收回</a></li>';
            html += '<li><a href="#!" id="delete">删除</a></li>';
            html += '</ul></div>'
        } else {
            html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
            html += '<li><a href="#!" id="retrieve">收回</a></li>';
            html += '<li><a href="#!" id="delete">删除</a></li>';
            html += '</ul></div>'
        }
    }
    return html;
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        var poolId = $("#poolId").val();
        var poolCategory = $("#poolCategory").val();
        var poolState = $("#poolState").val();
        var defaultMark = $("#defaultMark").val();
        var allocation = $("#allocation").val();
        //详情
        parent.$(parent.document).data('multitabs').create({
            iframe: true,
            title: '线索详情',
            url: "/front/cluePoolManager/clueDetail?clueId=" + row.clueId + "&poolId=" + poolId + "&poolCategory="
                + poolCategory + "&poolState=" + poolState + "&defaultMark=" + defaultMark + "&allocation=" + allocation
        }, true);
    },
    //分配点击事件
    'click #distribution': function (e, value, row, index) {
        var poolId = $("#poolId").val();
        if (poolState == 2) {
            $.alert("线索池已停用不能分配");
            return;
        }
        if (row.clueState != '在池') {
            if (row.clueState) {
                $.alert("线索" + row.clueState + "不能重复分配");
            } else {
                $.alert("线索已被领取或分配，不能重复分配");
            }
            return;
        }

        //全国公有池
        if (poolCategory == 3) {
            loadAllCompanyList(); //加载全国公司
        }

        //分公司公有池
        if (poolCategory == 2) {
            loadBranchCompanyList(poolId);
        }

        if (poolCategory == 1) {
            loadPrivateCompanyAndPerson(poolId);
        }
        $("#clueId").val(row.clueId);
        $('#clueDistributeModal').modal('show');
    },
    //收回点击事件
    'click #retrieve': function (e, value, row, index) {
        retrieveClueClick(row.clueId, row.clueState,row.cluePoolPrivateId);
    },
    //删除点击事件
    'click #delete': function (e, value, row, index) {
        deleteClueClick(row.clueId, row.clueState);
    },
};

/**
 * 拼接线索池表格查询条件参数
 */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //普通搜索条件
    params.poolId = $('#poolId').val();
    params.poolCategory = $('#poolCategory').val();//线索池类别
    params.companyName = $.trim($('#companyName').val());//公司名称
    params.clueNumber = $.trim($('#clueNumber').val());//线索ID
    params.source = $.trim($('#source').val());//线索来源
    params.clueState = $('#clueStateSelect option:selected').val();//线索状态
    params.defaultMark = $('#defaultMark').val();
    return params;
}

/**
 * 线索清单--搜索点击事件
 */
function searchClueTableList(type) {
    if (type == 1) {//普通搜索点击事件
        $clueTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单 需传入高级搜索id #filterContent
        resetData('#filterContent');
        $('#filterContent').collapse('hide');
    } else {//高级搜索点击事件
        $clueTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }
}

/**
 * 线索清单--高级搜索点击事件
 */
function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.defaultMark = $('#defaultMark').val();//是否是默认池

    //清空普通搜索条件
    $('#companyName').val('');

    var industry = $('#industrySelect option:selected').val();//行业
    var enterpriseType = $('#enterpriseTypeSelect option:selected').val();//企业类型

    var yearsEstablishmentSelect = $('#yearsEstablishmentSelect option:selected').val();//成立年限
    /**自定义成立年限**/
    var beginYearsEstablishmentCustom = $('#beginYearsEstablishment').val();
    var endYearsEstablishmentCustom = $('#endYearsEstablishment').val();
    var beginYearsEstablishment;
    var endYearsEstablishment;
    if(yearsEstablishmentSelect == 1){//1年内
        endYearsEstablishment = 0;
    }else if(yearsEstablishmentSelect == 2){//1-3年
        beginYearsEstablishment = 1;
        endYearsEstablishment = 3
    }else if(yearsEstablishmentSelect == 3){//3-5年
        beginYearsEstablishment = 3;
        endYearsEstablishment = 5;
    }else if(yearsEstablishmentSelect == 4){//5-10年
        beginYearsEstablishment = 5;
        endYearsEstablishment = 10;
    }else if(yearsEstablishmentSelect == 5){//10年以上
        beginYearsEstablishment = 11;
    }

    if(beginYearsEstablishmentCustom){
        beginYearsEstablishment = beginYearsEstablishmentCustom;
    }
    if(endYearsEstablishmentCustom){
        endYearsEstablishment = endYearsEstablishmentCustom;
    }

    var registeredCapitalSelect = $('#registeredCapitalSelect option:selected').val();//注册资本
    /**自定以注册资本**/
    var beginRegisteredCapitalCustom = $('#beginRegisteredCapital').val();
    var endRegisteredCapitalCustom = $('#endRegisteredCapital').val();
    var beginRegisteredCapital;
    var endRegisteredCapital;
    if(registeredCapitalSelect){
        if(registeredCapitalSelect == 1){//100万以内
            endRegisteredCapital = 99;
        }else if(registeredCapitalSelect == 2){//100万-500万
            beginRegisteredCapital = 100;
            endRegisteredCapital = 500;
        }else if(registeredCapitalSelect == 3){//500万-1000万
            beginRegisteredCapital = 500;
            endRegisteredCapital = 1000;
        }else if(registeredCapitalSelect == 4){//1000万-3000万
            beginRegisteredCapital = 1000;
            endRegisteredCapital = 3000;
        }else if(registeredCapitalSelect == 5){//3000万-5000万
            beginRegisteredCapital = 3000;
            endRegisteredCapital = 5000;
        }else if(registeredCapitalSelect == 6){//5000万以上
            beginRegisteredCapital = 5001;
        }
    }
    if(beginRegisteredCapitalCustom ){
        beginRegisteredCapital = beginRegisteredCapitalCustom;
    }
    if(endRegisteredCapitalCustom ){
        endRegisteredCapital = endRegisteredCapitalCustom;
    }

    var insuredNumbersSelect = $('#insuredNumbersSelect option:selected').val();//参保人数
    /**自定义参保人数**/
    var beginInsuredNumbersCustom = $('#beginInsuredNumbers').val();
    var endInsuredNumbersCustom = $('#endInsuredNumbers').val();
    var beginInsuredNumbers;
    var endInsuredNumbers;
    if(insuredNumbersSelect){
        if(insuredNumbersSelect == 1){//5人以下
            endInsuredNumbers = 4;
        }else if(insuredNumbersSelect == 2){//5-10人
            beginInsuredNumbers = 5;
            endInsuredNumbers = 10;
        }else if(insuredNumbersSelect == 3){//10-20人
            beginInsuredNumbers = 10;
            endInsuredNumbers = 20;
        }else if(insuredNumbersSelect == 4){//20-100人
            beginInsuredNumbers = 20;
            endInsuredNumbers = 100;
        }else if(insuredNumbersSelect == 5){//100-500人
            beginInsuredNumbers = 100;
            endInsuredNumbers = 500;
        }else if(insuredNumbersSelect == 6){//500-1000人
            beginInsuredNumbers = 500;
            endInsuredNumbers = 1000;
        }else if(insuredNumbersSelect == 7){//1000人以上
            beginInsuredNumbers = 1001;
        }
    }
    if(beginInsuredNumbersCustom ){
        beginInsuredNumbers = beginInsuredNumbersCustom;
    }
    if(endInsuredNumbersCustom ){
        endInsuredNumbers = endInsuredNumbersCustom;
    }

    var contactPersonPhone =  $('#isExistContactPersonPhone option:selected').val();//是否有联系电话
    var contactPerson =  $('#isExistContactPerson option:selected').val();//是否有联系人
    var companyEmail =  $('#isExistCompanyEmail option:selected').val();//是否有联系邮箱

    params.poolId = $('#poolId').val();
    params.poolCategory = $('#poolCategory').val();//线索池类别
    params.industry = industry;
    params.enterpriseType = enterpriseType;
    params.beginYearsEstablishment = beginYearsEstablishment;
    params.endYearsEstablishment = endYearsEstablishment;
    params.beginRegisteredCapital = beginRegisteredCapital;
    params.endRegisteredCapital = endRegisteredCapital;
    params.beginInsuredNumbers = beginInsuredNumbers;
    params.endInsuredNumbers = endInsuredNumbers;
    params.contactPersonPhone = contactPersonPhone;
    params.contactPerson = contactPerson;
    params.companyEmail = companyEmail;
    params.clueState = $('#clueStateSelect option:selected').val();//线索状态
    return params;
}

// 修改  提交
function editContent() {
    if ($("#addDetail").prop('disabled')) {
        $('.power-box').removeClass('power-disable');
        $("#addDetail").prop('disabled', false);
        $("#editBtn").html('<label><i class="mdi mdi-check"></i></label>提交').removeClass('btn-primary').addClass('btn-success');
        $("#editBtn").next('.btn-default').fadeIn();
    } else {
        $('.power-box').addClass('power-disable');
        $("#addDetail").prop('disabled', true);
        $('#editBtn').html('<label><i class="mdi mdi-pencil"></i></label>修改').removeClass('btn-success').addClass('btn-primary');
        $("#editBtn").next('.btn-default').fadeOut();
        // 提交用到的数据

        // var nodes = treeObj.getCheckedNodes(true);

        var poolId = $("#poolId").val();
        var poolDetail = $('#addDetail').val();//线索池详情
        var jsonData = {
            "cluePoolId": poolId,
            "managerPeopleIdList": optionObj,
            "poolDetail": poolDetail,
            'useCompanyIdList': peopleOptionObj,
            'usePeopleList': mainTreeData
        };
        $.ajax({
            url: '/cluePoolPublic/saveCluePoolPermissionAndDetail',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == "000000") {
                    $.alert({
                        title: '提示',
                        content: '保存成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                }
                            }
                        }
                    });
                } else {
                    alert("保存失败");
                }
            }),
            error: (function (res) {
                alert("保存失败");
            })
        });
    }
}

// 取消编辑
function editCancel(_this) {
    $('.power-box').addClass('power-disable');
    $("#addDetail").prop('disabled', true);
    $(_this).hide(0).prev('button').html('<label><i class="mdi mdi-pencil"></i></label>修改').removeClass('btn-success').addClass('btn-primary');
}

// 新增线索
function goAddNew() {
    <!--线索池主键-->
/*<input type="hidden" id="poolId" name="poolId" th:value="${poolId}"/>
        <!--线索池类别(0:个人池;1:私有池;2:分公司公有池;3:全国公有池)-->
    <input type="hidden" id="poolCategory" name="poolCategory" th:value="${poolCategory}"/>
        <!--线索池停用/启用状态(1:开启;2:停用)-->
    <input type="hidden" id="poolState" name="poolState" th:value="${poolState}"/>
        <!--是否是默认池子(0:不是默认;1:默认池子)-->
    <input type="hidden" id="defaultMark" name="defaultMark" th:value="${defaultMark}"/>
        <!--分配方式(0:混合模式;1:被动分配)-->
    <input type="hidden" id="allocation" name="allocation" th:value="${allocation}"/>
        <!--是否显示权限与详情tab页-->
        <input type="hidden" id="poolPermissionFlag" name="poolPermissionFlag" th:value="${poolPermissionFlag}">*/
    var poolId = $("#poolId").val();
    var poolCategory = $("#poolCategory").val();
    var poolState = $("#poolState").val();
    var defaultMark = $("#defaultMark").val();
    var allocation = $("#allocation").val();
    var poolPermissionFlag = $("#poolPermissionFlag").val();
    var companyId = $("#companyId").val();
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增线索',
        url: "/front/cluePoolManager/addClue?poolId=" + poolId + "&poolCategory=" + poolCategory +
            "&poolState=" + poolState + "&defaultMark=" + defaultMark + "&allocation=" + allocation +
            "&poolPermissionFlag=" + poolPermissionFlag + "&companyId=" + companyId
    }, true);
}

// 选择人的弹层
/*function choosePeople() {
    $('#peopleModal').modal('show');
    //$('#nameList').html(' ');
}*/

// 回显选中的人员
//分配人员名单
var assignedPersonList = [];
var assignedPersonNameList = [];
var strHtml = '';

function getPeopleShow() {
    $('#nameList ul').html(' ');
    //选择的审批人
    for (let i = 1; i < num + 1; i++) {
        let obj = {};
        let objName = {};
        obj.companyId = $("#deptSelect" + i).val();
        objName.companyName = $("#deptSelect" + i).find("option:selected").text();
        obj.peopleId = $("#personSelect" + i).val();
        objName.approverName = $("#personSelect" + i).find("option:selected").text();
        assignedPersonList.push(obj);
        assignedPersonNameList.push(objName);
    }
    for (let m = 0; m < assignedPersonNameList.length; m++) {
        strHtml += '<div class="bu-ren form-control">\n' +
            '<span class="bumen">' + assignedPersonNameList[m].companyName + '</span>\n' +
            '<span class="renyuan">' + assignedPersonNameList[m].approverName + '</span>\n' +
            '</div>'
    }
    $('#nameList ul').append(strHtml);
}

function changeWay(type) {
    if (type == 0) {
        $('.three').css('display', 'none');
        $('.one').css('display', 'block');
    }
    if (type == 1) {
        $('.one').css('display', 'none');
        $('.three').css('display', 'block');
        $('#companyList').selectpicker('refresh');
    }
}


/**
 * 被动分配人员名单功能
 * */
// 获取部门列表
function getCompany() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            data.data.map(function (item) {
                optionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#companyList').html(optionHtml);
            // getPerson(data.data[0].companyId);
        }
    });
    // 部门改变更新人员列表
    $("select[id*='companyList']").on("change", function () {
        getPerson($(this).val());
    })
}
// 获取人员列表
function getPerson(companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var optionPersonHtml = '';
            data.data.map(function (item) {
                optionPersonHtml += '<option value="' + item.accountId + '">' + item.userName + '</option>';
            });
            $('#personList').html(optionPersonHtml);
            $('#personList').selectpicker('refresh');
        }
    });
}
// 添加 被动分配人员名单
function addList() {
    var companyId = $('#companyList').val();
    var companyName = $('#companyList').find("option:selected").text();
    var personId = $('#personList').val();
    var personName = $('#personList').find("option:selected").text();

    // 判断是否为空
    if (companyId === '' || personId == '') {
        promptInfo('添加名单不能为空，请重新选择！');
        return false;
    }

    // 判断名单人员是否已添加
    for (var i = 0; i < $('#nameList li').length; i++) {
        if ($('#nameList li').eq(i).attr('data-company') === companyId && $('#nameList li').eq(i).attr('data-person') === personId) {
            promptInfo(personName + ' 已经添加到被动分配人员名单！');
            return false;
        }
    }
    // 添加名单到列表
    var nameList = '<li data-company="' + companyId + '" data-person="' + personId + '"><span class="company">' + companyName + '</span><span class="person">' + personName + '</span><a href="JavaScript:void(0);" onclick="deleteList(this);"><i class="mdi mdi-close"></i></a></li>';
    $('#nameList ul').append(nameList);
}

// 删除已添加名单
function deleteList(obj) {
    $(obj).parents('li').remove();
}

/**
 * 线索--收回
 * @param clueId     --线索主键
 * @param status     --线索状态(在池和已转化为客户的线索不能收回)
 * @param cluePoolPrivateId --从哪个池子收回的池子id
 */
var clueId;
var clueState;
var cluePoolFromId;
function retrieveClueClick(id, status,cluePoolPrivateId) {
    clueState = status;
    clueId = id;
    cluePoolFromId = cluePoolPrivateId;
    if (clueState == '在池') {
        $.alert("线索未分配或未领取,不能收回!");
        return;
    }else if(clueState == '已转化'){
        $.alert("线索已转化为客户,不能收回!");
        return;
    }
    $('#retrieveClueModal').modal('show');
}

/**
 * 线索--收回确定点击事件
 */
function confirmRetrieveClue() {
    var returnReason = $('#returnReason').val();//线索收回原因
    if(!returnReason){
        $.alert("收回原因不能为空");
        return;
    }
    $.alert({
        title: '提示',
        content: "确定要收回吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/clue/retrieveClue",
                        data: {
                            clueId: clueId,
                            returnReason:returnReason,
                            cluePoolToId: cluePollId,
                            cluePoolFromId:cluePoolFromId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('操作成功!');
                                $clueTable.bootstrapTable('updateCellById', {
                                    id: clueId,
                                    field: 'clueState',
                                    value: '在池'
                                });
                                tableNav();
                            } else {
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });
    $('#retrieveClueModal').modal('hide');
}

/**
 * 关闭线索收回模态框
 */
function cancelRetrieveClue() {
    $('#retrieveClueModal').modal('hide');
}

/**
 * 线索--分配保存
 */
function distributeClueClick() {
    var distributeUserId = '';
    var clueId = $('#clueId').val();//线索ID
    var poolId = $('#poolId').val();//线索池ID
    if (poolCategory == 2 || poolCategory == 3) {//线索池类别(分公司公有池、全国公有池)
        var selectPeopleByCompany = $("input[name='people']:checked").val();//通过公司选人
        var selectPeopleByName = $('#choosedPeopleName').text();//通过人名选人
        var choosedPeopleId = $('#choosedPeopleId').val();
        if (selectPeopleByCompany && selectPeopleByName) {
            $.alert("线索只能分配给一个人,请重置选择");
            return;
        }
        if (selectPeopleByCompany) { //按公司选人
            distributeUserId = $("input[name='people']:checked").val();
        }
        if (choosedPeopleId) { //按人名选人
            distributeUserId = choosedPeopleId;
        }
    }
    if (poolCategory == 1) { //线索池类别(私有池)

    }
    if(!distributeUserId){
        $.alert("请选择一个人进行分配");
        return;
    }
    $.ajax({
        url: "/clue/distributeClue",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {
            distributeUserId: distributeUserId,
            clueId: clueId,
            poolId: poolId
        },
        success: function (data) {
            if (data.code == '000000'){//分配成功
                $.alert("操作成功！");
                $('#clueDistributeModal').modal('hide');
                $clueTable.bootstrapTable('refreshOptions', {pageNumber: 1});
            } else if (data.code == 'C00011'){//超出线索池容量
                $.alert(data.message);
            }else if(data.code == 'CP0001'){//没有个人默认池不能分配
                $.alert(data.message);
            } else {//操作失败
                $.alert('操作失败,请稍后再试');
            }
        },
        error: function () {
            $.alert('修改失败，请稍后再试!');
        }
    })
}

/**
 * 线索--删除
 * @param clueId     ---线索主键
 * @param clueState  ---线索状态
 */
function deleteClueClick(clueId, clueState) {
    if(clueState == "已转化"){
        $.alert("已转化为客户,不能删除!");
        return;
    }
    if (clueState != '在池') {
        $.alert("请先收回再删除!");
        return;
    }
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/clue/deleteClue",
                        data: {
                            clueId: clueId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('操作成功!');
                                $clueTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

/**
 * 线索池规则显示值
 */
function profileBasic() {
    var allocation = $("#allocation").val();
    var poolId = $("#poolId").val();
    if (allocation == 0) {
        $('#mixedMode').prop('checked', 'checked');
        $('#passiveAllocation').removeProp('checked');
        changeWay(0)
    } else if (allocation == 1) {
        $('#passiveAllocation').prop('checked', 'checked');
        $('#mixedMode').removeProp('checked');
        changeWay(1)
    }
    $.ajax({
        type: "post",
        url: "/cluePoolPublic/getCluePoolRule",
        data: {
            poolId: poolId
        },
        dataType: 'json',
        success: function (data, status) {
            if (data.code == '000000') {
                var cluePoolRule = data.data;
                var maximumNumber = cluePoolRule.maximumNumber;
                var collectionTimeInterval = cluePoolRule.collectionTimeInterval;
                var returnInterval = cluePoolRule.returnInterval;
                var allocationTimeInterval = cluePoolRule.allocationTimeInterval;
                var assignedQuantity = cluePoolRule.assignedQuantity;
                var continueTimeInterval = cluePoolRule.continueTimeInterval;
                console.log(assignedQuantity);
                if (allocation == 0) {
                    if (maximumNumber && maximumNumber != "null") {
                        $("#maximumNumber").val(maximumNumber);
                    }
                    if (collectionTimeInterval && collectionTimeInterval != "null") {
                        $("#timeInterval").val(collectionTimeInterval);
                    }
                    if (continueTimeInterval && continueTimeInterval != "null") {
                        $("#continueTimeInterval").val(continueTimeInterval);
                    }
                    if (returnInterval && returnInterval != "null") {
                        $("#returnInterval").val(returnInterval);
                    }
                } else if (allocation == 1) {
                    if (allocationTimeInterval && allocationTimeInterval != "null") {
                        $("#allocationTimeInterval").val(allocationTimeInterval);
                    }
                    if (assignedQuantity && assignedQuantity != "null") {
                        $("#assignedQuantity").val(assignedQuantity);
                    }
                    if (returnInterval && returnInterval != "null") {
                        $("#returnInterval").val(cluePoolRule.returnInterval);
                    }
                    var assignedPersons = cluePoolRule.assignedPersonList;
                    getAssignedPersonList(assignedPersons);


                    /*let html = '';
                    num = 1;
                    var length = $("#nameList ul").children().length;
                    for (let m = 1; m < length; m++) {
                        $('#nameList ul').children("#contentB" + (m + 1)).remove();
                    }
                    for (let i = 0; i < assignedPersons.length; i++) {
                        // console.log(assignedPersons)

                        var personId = assignedPersons[i].peopleId;
                        var companyId = assignedPersons[i].companyId;

                        /!*if (i == 0) {
                            getCheckedDept(num, peopleId, companyId);
                            getCheckedPeople(num, peopleId, companyId);
                        } else {

                            /!*nameList = '<li data-company="' + companyId + '" data-person="' + personId + '">' +
                                '<span class="company">' + companyName + '</span>' +
                                '<span class="person">' + personName + '</span>' +
                                '<a href="JavaScript:void(0);"><i class="mdi mdi-close"></i></a></li>';*!/

                            num++;
                            html = '<div id="contentB' + num + '" style="display: flex;min-width: 140px;margin-bottom: 10px;">\n' +
                                '<select  id="deptSelect' + num + '" style="width: 204px;margin-right: 30px;" class="form-control" data-live-search="true"></select>\n' +
                                '<select id="personSelect' + num + '" style="width: 204px;margin-right: 30px;" class="form-control col-sm-2" data-live-search="true" ></select>\n' +
                                '<div onclick="deleteDept(num)" id="delete' + num + '" style="cursor:pointer;padding: 8px 0;color: #ccc;">删除</div>\n' +
                                '</div>';
                            $('#nameList ul').append(html);
                            getCheckedDept(num, peopleId, companyId);
                            getCheckedPeople(num, peopleId, companyId);
                        }*!/
                    }*/
                }
            }
        },
        error: function () {
        }
    });

}

function getAssignedPersonList(assignedPersons) {
    $('#nameList ul').html(' ');

    //选择的审批人
    var nameList = '';
    for (let i = 0; i < assignedPersons.length; i++) {
        nameList += '<li data-company="' + assignedPersons[i].companyId + '" data-person="' + assignedPersons[i].peopleId + '">' +
            '<span class="company">' + assignedPersons[i].companyName + '</span>' +
            '<span class="person">' + assignedPersons[i].approverName + '</span>' +
            '<a href="JavaScript:void(0);" onclick="deleteList(this);"><i class="mdi mdi-close"></i></a></li>';
    }
    $('#nameList ul').append(nameList);
}

// 获取部门
function getCheckedDept(id, peopleId, companyId) {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            data.data.map(function (item) {
                var isSelect = item.companyId === companyId ? 'selected' : '';

                optionHtml += '<option value="' + item.companyId + '"' + isSelect + '>' + item.companyName + '</option>';
            });
            $('#deptSelect' + id).html(optionHtml);
        }
    });
}

// 获取人员
function getCheckedPeople(id, peopleId, companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var optionPersonHtml = '';
            data.data.map(function (item) {
                var isSelect = item.accountId === peopleId ? 'selected' : '';
                optionPersonHtml += '<option value="' + item.accountId + '"' + isSelect + '>' + item.userName + '</option>';
            });
            $('#personSelect' + id).html(optionPersonHtml);
        }
    });
}

function cancelUpdateCluePoolRule() {
    $("#maximumNumber").val("");
    $("#timeInterval").val("");
    $("#continueTimeInterval").val("");
    $("#returnInterval").val("");
    $("#allocationTimeInterval").val("");
    $("#assignedQuantity").val("");
    $('#nameList ul').html('');
    profileBasic();
}

/**
 * 修改线索池规则
 */
function updateCluePoolRule() {
    //线索池主键
    var poolId = $("#poolId").val();

    //线索池分配方式
    var allocation = $("input[name='allocationRadio']:checked").val();

    //无跟进退回时间间隔
    var returnInterval = $("#returnInterval").val();

    //最多领取数量
    var maximumNumber = $("#maximumNumber").val();

    //领取时间间隔
    var collectionTimeInterval = $("#timeInterval").val();

    //同一线索不能连续领取间隔
    var continueTimeInterval = $("#continueTimeInterval").val();

    //分配数量
    var assignedQuantity = $("#assignedQuantity").val();

    //分配时间间隔
    var allocationTimeInterval = $("#allocationTimeInterval").val();

    var length = $("#nameList ul").children().length;

    //分配人员名单
    var assignedPersonList = [];
    //选择的审批人
    /*for (let i = 1; i < num + 1; i++) {
        let obj = {};
        obj.companyId = $("#deptSelect" + i).val();
        obj.peopleId = $("#personSelect" + i).val();
        assignedPersonList.push(obj)
    }*/
    for (let i = 0; i < $('#nameList ul li').length; i++) {
        let obj = {};
        obj.companyId = $('#nameList ul li').eq(i).attr('data-company');
        obj.peopleId = $('#nameList ul li').eq(i).attr('data-person');
        assignedPersonList.push(obj)
    }

    //线索池分配方式
    if (!allocation) {
        promptInfo("分配方式必选！");
        return;
    }

    //最多领取数量
    if (allocation == 0 && !maximumNumber) {
        promptInfo("最多领取数量必填！");
        return;
    } else if (eval(maximumNumber) > eval("2147483647")) {
        promptInfo("最多领取数量值太大！");
        return;
    }

    //领取时间间隔
    if (allocation == 0 && !collectionTimeInterval) {
        promptInfo("最多领取数领取时间间隔必填！");
        return;
    } else if (eval(collectionTimeInterval) > eval("2147483647")) {
        promptInfo("最多领取数领取时间间隔值太大！");
        return;
    }

    //无跟进时间间隔验证
    if (!returnInterval) {
        promptInfo("无跟进退回时间间隔必填！");
        return;
    } else if (eval(returnInterval) > eval("2147483647")) {
        promptInfo("无跟进退回时间间隔值太大！");
        return;
    }

    //分配时间间隔
    if (allocation == 1 && !allocationTimeInterval) {
        promptInfo("分配时间间隔必填！");
        return;
    } else if (eval(allocationTimeInterval) > eval("2147483647")) {
        promptInfo("分配时间间隔必填值太大！");
        return;
    }

    //分配数量
    if (allocation == 1 && !assignedQuantity) {
        promptInfo("分配数量必填！");
        return;
    } else if (eval(assignedQuantity) > eval("2147483647")) {
        promptInfo("分配数量值太大！");
        return;
    }

    //被动分配人员名单
    if (allocation == 1 && length == 0) {
        promptInfo("被动分配人员名单必填！");
        return;
    }

    var jsonData = {
        "poolId": poolId,
        "allocation": allocation,
        "returnInterval": returnInterval,
        "maximumNumber": maximumNumber,
        "collectionTimeInterval": collectionTimeInterval,
        "continueTimeInterval":continueTimeInterval,
        "assignedQuantity": assignedQuantity,
        "allocationTimeInterval": allocationTimeInterval,
        "assignedPersonList": assignedPersonList

    };
    $.ajax({
        url: '/cluePoolPublic/updateCluePoolRule',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                promptInfo("保存成功");
                $("#allocation").val(allocation);
                cancelUpdateCluePoolRule();
            } else {
                promptInfo("保存失败");
            }
        }),
        error: (function (res) {
            promptInfo("保存异常");
        })
    });
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

//  重置
function resetData(_this) {
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    }else{
        searchForm = $(_this).parents('#filterContent');
    }

    // 重置表单内容
    searchForm.find('input[type="text"]').val('');
    searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');
    // 重置自定义筛选条件
    searchForm.find('.custom-group').find('input[type="checkbox"]').prop('checked', false);
    searchForm.find('.custom-group').removeClass('custom-active').find('select').removeAttr('disabled').selectpicker('refresh');
    searchForm.find('.custom-group').find('input[type="text"]').val('');

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        searchClueTableList();
    }
}

function formReset(){
    $('#returnInterval').val('')
    $('#allocationTimeInterval').val('');
    $('#assignedQuantity').val('');
    $('#companyList').val('');
    $('#maximumNumber').val('');
    $('#timeInterval').val('');
    $('#continueTimeInterval').val('')
    $('#companyList').selectpicker('refresh');
    $('#personList').val('');
    $('#personList').selectpicker('refresh');
    $('#nameList ul').html('');
}

//显示导入线索模态框
function showImportClueModal(){
    $('#importClueModal').modal('show');
}

//取消导入线索模态框
function cancelImportClueList() {
    $("#importClueFile").val("");
}

//导入线索名单
function importClueList() {
    //线索池主键
    var poolId = $("#poolId").val();
    if(!document.getElementById('importClueFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importClueFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importClueFile")[0].files[0]);
    //是否是私有池标记
    if(poolCategory=='0'){
        //private表
        formData.append("clueType",2);
    }else {
        //public表
        formData.append("clueType",1);
    }

    formData.append("clueStatus",0);
    formData.append("poolId",poolId);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/clueImport/clueImport',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    //线索导入数量
                    var importClueNum = data.data.importClueNum;
                    var repeatIdStr = data.data.repeatIdStr;
                    var importFailIdStr = data.data.importFailIdStr;

                    //返回内容
                    var content = "";

                    //导入数量大于0
                    if(importClueNum>0){
                        content = "成功导入"+importClueNum+"条数据";
                    }
                    //重复id不为空
                    if(repeatIdStr!=""){
                        content = content + "<br>第：" + repeatIdStr + "行数据库已存在，导入失败";
                    }
                    //失败id不为空
                    if(importFailIdStr!=""){
                        content = content + "<br>第：" + importFailIdStr + "行数据导入失败";
                    }

                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importClueFile").val("");
                                    $clueTable.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importClueModal').modal('hide');
                    $("#importClueFile").val("");
                }else if(data.code == "CI0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importClueFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importClueFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importClueFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}

//下载线索模板
function downClueTemplate(){
    var url="/clueImport/downloadClueTemplate";
    window.location.href=encodeURI(encodeURI(url));
}

//  获取线索池数据统计
function getClueData() {
    var poolId = $("#poolId").val();
    $.ajax({
        url: "/cluePoolStatistics/cluePoolLeftStatistics?cluePoolId="+poolId,
        async: false,
        type: "get",
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                $("#allClueNumber").text(data.data.clueTotalCount);
                $("#allGetClue").text(data.data.clueReceiveCount);
                $("#zero").text(data.data.clueZeroTimeReceiveCount);
                $("#freeNumber").text(data.data.idleCount);
                //$("#changeNumber").text(0); // 目前写死 data.data.conversionsCount
                $("#changeNumber").text(data.data.conversionsCount);
                $("#followNumber").text(data.data. followCount);
                $("#poolUsageCount").text(data.data.poolUsageCount);
            }
        }
    })
}